package com.core.shared;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/3/18
 * Time: 14:58
 * To change this template use File | Settings | File Templates.
 */
public class AIOHandle {

    public final static int port = 9888;
    private AsynchronousServerSocketChannel server;

    public AIOHandle() throws IOException {
        server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
    }

    public void startWithFuture() throws ExecutionException, InterruptedException, TimeoutException {
        while (true) {
            System.out.println("server listen on " + port);
            Future<AsynchronousSocketChannel> future = server.accept();
            AsynchronousSocketChannel socket = future.get();
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            readBuffer.clear();
            socket.read(readBuffer).get(100, TimeUnit.SECONDS);
            readBuffer.flip();
            System.out.printf("received message:" + new String(readBuffer.array()));
            System.out.println(Thread.currentThread().getName());
        }
    }

    public void startWithCompletionHandler() throws InterruptedException,
            ExecutionException, TimeoutException {
        System.out.println("Server listen on " + port);
        //注册事件和事件完成后的处理器
        server.accept(null,
                new CompletionHandler<AsynchronousSocketChannel, Object>() {
                    final ByteBuffer buffer = ByteBuffer.allocate(1024);

                    @Override
                    public void completed(AsynchronousSocketChannel result, Object attachment) {
                        System.out.println(Thread.currentThread().getName());
                        System.out.println("start");
                        try {
                            buffer.clear();
                            result.read(buffer).get(100, TimeUnit.SECONDS);
                            buffer.flip();
                            System.out.println("received message: " + new String(buffer.array()));
                        } catch (InterruptedException | ExecutionException e) {
                            e.printStackTrace();
                        } catch (TimeoutException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                result.close();
                                server.accept(null, this);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("end");
                    }

                    @Override
                    public void failed(Throwable exc, Object attachment) {
                        System.out.println("failed: " + exc);
                    }
                });
        while (true) {
//            System.out.println("main thread");
            Thread.sleep(1000);
        }

    }

    public static void main(String[] args) throws Exception {
//        new AIOHandle().startWithCompletionHandler();
        new AIOHandle().startWithFuture();
    }

}
